print("--- SCRIPT VERSION 2.0 --- THIS IS THE LATEST CODE ---")
import os
import requests
import pandas as pd
import re

# --- 配置 ---
# 从环境变量中读取 GitLab URL 和私有访问令牌
GITLAB_URL = os.getenv('GITLAB_URL', 'http://10.28.120.90')
PRIVATE_TOKEN = os.getenv('GITLAB_PRIVATE_TOKEN')
ASSIGNEE_USERNAME = 'meihaohui'
OUTPUT_FILE = f'gitlab_issues_{ASSIGNEE_USERNAME}.xlsx'

# API请求头
headers = {
    'PRIVATE-TOKEN': PRIVATE_TOKEN
}

# 需要导出的字段
FIELDS = [
    'id', 'iid', 'project_id', 'title', 'description', 'state', 'created_at',
    'updated_at', 'closed_at', 'author', 'assignee', 'labels', 'web_url'
]

def fetch_all_issues():
    """
    通过分页获取所有相关的问题
    """
    issues = []
    page = 1
    while True:
        params = {
            'assignee_username': ASSIGNEE_USERNAME,
            'scope': 'all',
            'per_page': 100,
            'page': page
        }
        print(f"正在获取第 {page} 页的问题...")
        try:
            response = requests.get(f"{GITLAB_URL}/api/v4/issues", headers=headers, params=params, verify=False)
            response.raise_for_status()  # 如果请求失败则抛出异常
            
            data = response.json()
            if not data:
                break
            
            issues.extend(data)
            page += 1
        except requests.exceptions.RequestException as e:
            print(f"请求API时发生错误: {e}")
            if e.response is not None and e.response.status_code == 401:
                print("错误：认证失败 (401)。请检查你的 GITLAB_PRIVATE_TOKEN 是否正确并拥有 'read_api' 权限。")
            return None

    return issues

def main():
    """
    主函数
    """
    if not PRIVATE_TOKEN:
        print("错误：请设置 GITLAB_PRIVATE_TOKEN 环境变量。")
        print("你可以从 GitLab 的 '个人资料 -> 偏好设置 -> 访问令牌' 页面创建。")
        return

    print(f"开始从 {GITLAB_URL} 导出用户 '{ASSIGNEE_USERNAME}' 的问题...")
    
    all_issues = fetch_all_issues()

    if all_issues is None:
        print("获取问题失败，脚本终止。")
        return

    if not all_issues:
        print("没有找到符合条件的问题。")
        return

    print(f"总共找到 {len(all_issues)} 个问题。")
    
    # 提取所需数据
    issues_data = []
    for issue in all_issues:
        # 处理 author 和 assignee 字段，提取 username
        author_username = issue['author']['username'] if issue.get('author') else 'N/A'
        assignee_username = issue['assignee']['username'] if issue.get('assignee') else 'N/A'

        # --- 新增功能：解析描述中的图片链接 ---
        description = issue.get('description') or ''
        web_url = issue.get('web_url', '')

        
        picture_urls = []

        if '/-/issues/' in web_url:
            project_url = web_url.split('/-/issues/')[0]
            # 查找所有符合条件的 markdown 图片链接
            relative_paths = re.findall(r"!\[.*?\]\((/uploads/[^)]+)\)", description)
            
            for path in relative_paths:
                picture_urls.append(f"{project_url}{path}")
        
        # 从描述中移除已提取的 markdown 图片链接
        cleaned_description = re.sub(r"\!\[.*?\]\(/uploads/[^)]+\)\s*", "", description).strip()
        
        
        # --- 功能结束 ---

        issue_info = {
            'id': issue.get('id'),
            'iid': issue.get('iid'),
            'project_id': issue.get('project_id'),
            'title': issue.get('title'),
            'description': cleaned_description,
            'picture': '\n'.join(picture_urls),
            'state': issue.get('state'),
            'created_at': issue.get('created_at'),
            'updated_at': issue.get('updated_at'),
            'closed_at': issue.get('closed_at'),
            'author': author_username,
            'assignee': assignee_username,
            'labels': ', '.join(issue.get('labels', [])),
            'web_url': issue.get('web_url')
        }
        issues_data.append(issue_info)
        
    # 创建 DataFrame 并导出到 Excel
    df = pd.DataFrame(issues_data)
    
    try:
        df.to_excel(OUTPUT_FILE, index=False, engine='openpyxl')
        print(f"成功！问题已导出到文件: {os.path.abspath(OUTPUT_FILE)}")
    except Exception as e:
        print(f"导出到Excel时发生错误: {e}")

if __name__ == "__main__":
    # 禁用requests的InsecureRequestWarning警告
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    main() 